---------------------------------------------------------------------------------------
----------  DigiLinX HVAC driver for Proliphix thermostats
----------
----------  Top level driver for the Proliphix thermostats connected to the DigiLinx system.
----------  Each thermostat is wrapped in a ProliphixAdapter, which
----------  manages the socket connection with the Proliphix web server.
----------
----------  This driver file is meant to be used with the HVAC interface (refered to as
----------  AprilAire in dealer setup). I depends upon the following lua scripts which should
----------  accompany this file:
----------      -http.lua - a high level API wrapper for the HTTP module
----------      -httpPrivate.lua - the actual implementation of HTTP for Digi
----------      -url.lua - methods to maipulate URIs
----------      -proliphixAdapter.lua - module that wraps the Proliphix HTTP API
----------  Instructions on how to load the additional files can be found in the ReadMe
----------
----------  This driver can be used with Proliphix emulators that were written in ASP.
----------  This allows one to develop against the Proliphix API using a standard WIndows XP
----------  machine without requiring access to a functioning Proliphix thermostat.
----------  The Proliphix driver is available on my blog, along with information on how to use it:
----------  http://wiredright.wordpress.com/
----------
----------  Written by: Josh Kewley
----------              Insario Corporation
----------  Version:    0.85
----------  Date: 09/04/2007
---------------------------------------------------------------------------------------
local URL = require "url"
local HTTP = require "http"
local PROLIPHIX = require "proliphixadapter"
RevisionNumber="0.63"
debug("status", "Proliphix Driver Version # "..RevisionNumber)

setDebug("all", "off")

setDebug("Error", "on")             -- reporting of error messages
setDebug("Proliphix", "on")         -- standard Proliphix messages from this file and proliphixAdapter.lua
setDebug("ProliphixDetail", "on")   -- more detailed Proliphix messages from proliphixAdapter.lua, used in debugging
setDebug("status", "on")
setDebug("Http", "on")              -- standard Http messages from http.lua
setDebug("HttpSocket", "on")        -- more detailed Http socket messages from httpPrivate.lua, used in debugging
setDebug("HttpDetail", "on")        -- more detailed Http messages from httpPrivate.lua, used in debugging
--[[
setDebug("HttpStream", "on")        -- more detailed Http stream messages from httpPrivate.lua, used in debugging
setDebug("URL", "on")
setDebug("streamControl", "on")
setDebug("Trace", "on")
]]
debug("status", "Http library version "..HTTP.RevisionNumber)
debug("status", "URL library version "..URL.RevisionNumber)
debug("status", "Proliphix library version "..PROLIPHIX.RevisionNumber)

--  The list of IP addresses that designate thermostats must appear in the order in which they have been placed in
--  the AprilAire Label configuration in Dealer Setup.
--  10.15.15.31 - Living Room
--  10.15.15.32 - MBR2
--  10.15.15.33 - MBR1
thermostatIPlist = {"10.15.15.55","10.15.15.56"}
AllThermostats = {}
userName="testuser"
password="p@ssword1"

refreshFrequency = 10 * 1000  -- Frequency with which the thermostat status is refreshed. Proliphix calls for this to be once every 60 seconds.
nextRefreshIndex = 1          -- index of the next thermostat to be refreshed

-- encapsulate debugging
function DBG(message)
    debug("Proliphix", HTTP.makeReadable(message))
end

-- Iterate through the array if IP addresses
-- and use them to create Proliphix instances
for stat=1, #thermostatIPlist do
    local IP = thermostatIPlist[stat]
    DBG("Create thermostat #"..stat.." @ "..IP)
    local proliphix = PROLIPHIX:new()
    proliphix:Init(IP, userName, password, stat)
    proliphix:RefreshData()
    AllThermostats[stat] = proliphix
    os.sleep(5000) -- wait five seconds between the creation of each thermostat
end

DBG("All thermostats bound")

function PauseQueues()
  for stat=1, #AllThermostats do
    local aStat = AllThermostats[stat]
    aStat:PauseQueue()
  end
end
function ResumeQueues()
  for stat=1, #AllThermostats do
    local aStat = AllThermostats[stat]
    aStat:ResumeQueue()
  end
end
-- Run RefreshData on the thermostat objects with the frequency specified in refreshFrequency
start = function()
  debug("fire up proliphix driver")
  local hardReference = createTimer(refreshFrequency, function(timer)
                                                        timer:cancel()
                                                        PauseQueues()
                                                        local aStat = AllThermostats[nextRefreshIndex]
                                                        if(aStat == nil) then
                                                          DBG("YIKES! Thermostat "..tostring(nextRefreshIndex).." is NIL!")
                                                        else
                                                          DBG("Refresh thermostat "..tostring(aStat))
                                                          aStat:RefreshData()                                                        
                                                        end
                                                        if(nextRefreshIndex==#AllThermostats) then
                                                          nextRefreshIndex=1
                                                        else
                                                          nextRefreshIndex=nextRefreshIndex+1
                                                        end
                                                        DBG("Done refreshing. Next is thermostat "..tostring(nextRefreshIndex))                                                        
                                                        timer:queue(refreshFrequency)
                                                        ResumeQueues()
                                                        return refreshFrequency
                                                    end)
end

stop = function()
  debug("shut down proliphix driver")
end